/* DOCUMENTACION:
 * http://android-developers.blogspot.com/2009/09/introduction-to-text-to-speech-in.html
 * http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/TextToSpeechActivity.html
 * http://espeak.sourceforge.net/
 * http://eyes-free.googlecode.com/svn/trunk/documentation/tutorial/tutorial.html
 */

package com.meslize.howyousay;

import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import com.meslize.util.dialog.Dialogs;

public class Main extends Activity {

    private Context context;

    private TextToSpeech mTts = null;
    private Button buttonRepeat;
    private EditText inputField;
    
    private String language = "";
    private String country	= "";
    private String countryDisplayName = "";
    
    public static final int MY_DATA_CHECK_CODE 	= 100;
    
    public boolean textToSpeechInit = false;
    
    private int languageSelected = 0;
    private int languageConfirmed = 0;
    
    private AlertDialog dialogLanguage;
    
    GoogleAnalyticsTracker tracker;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        context = this;        
        
        tracker = GoogleAnalyticsTracker.getInstance();
        // Start the tracker in manual dispatch mode...
        tracker.startNewSession(Constants.ANALYTICS_UA, this);
        
        // Look up the AdView as a resource and load a request.
        AdView adView = (AdView)this.findViewById(R.id.adView);
        adView.loadAd(new AdRequest());

        buttonRepeat = (Button) findViewById(R.id.button_repeat);
        buttonRepeat.setEnabled(false);
        
        inputField = (EditText) findViewById(R.id.input_field);

        checkTextToSpeech();
    }
    
    @Override
	protected void onResume() {
		super.onResume();
        
        tracker.trackEvent(
                Constants.ANALYTICS_CLICK_CATEGORY,  // Category
                Constants.ANALYTICS_CLICK_ACTION,  // Action
                Constants.ANALYTICS_START, // Label
                Constants.ANALYTICS_CLICK_VALUE); // Value
        
        
        tracker.trackPageView(Constants.ANALYTICS_START);
	}

	@Override
    public void onDestroy() {
    	super.onDestroy();
	    // Stop the tracker when it is no longer needed.
	    tracker.stopSession();
	    
        // Don't forget to shutdown!
        if (mTts != null) {
            mTts.stop();
            mTts.shutdown();
        }
    }
    
    public void repeat(View view){
    	repeatInput();
        tracker.trackEvent(
                Constants.ANALYTICS_CLICK_CATEGORY,  // Category
                Constants.ANALYTICS_CLICK_ACTION,  // Action
                Constants.ANALYTICS_REPEAT, // Label
                Constants.ANALYTICS_CLICK_VALUE); // Value
        
        
        tracker.trackPageView(Constants.ANALYTICS_REPEAT);
    }
    
    public void checkTextToSpeech(){
    	Intent checkIntent = new Intent();
    	checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
    	startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
    }

    private void repeatInput() {
    	if(inputField.getText() != null && inputField.getText().toString().equals("") == false){
            mTts.speak(inputField.getText().toString(),
                    TextToSpeech.QUEUE_FLUSH,  // Drop all pending entries in the playback queue.
                    null);
    	}
    }
    
    public TextToSpeech.OnInitListener onInitListener = new TextToSpeech.OnInitListener(){

		public void onInit(int status) {
	        if (status == TextToSpeech.SUCCESS) {
	        	textToSpeechInit = true;
	        	
				language = Locale.getDefault().getLanguage();
				country = Locale.getDefault().getCountry();
	        	
	            int result = mTts.isLanguageAvailable(new Locale(language, country));

	            setLanguage(result);
	        }
//	        else{
//	        	Toast.makeText(context, "Could not initialize TextToSpeech.", Toast.LENGTH_SHORT).show();
//	        }
		}	
    };
    
    public void setLanguage(int result){
        if (result == TextToSpeech.LANG_NOT_SUPPORTED) {
        	Toast.makeText(context, R.string.language_not_supported, Toast.LENGTH_SHORT).show();
        }else if(result == TextToSpeech.LANG_MISSING_DATA){
        	Toast.makeText(context, R.string.language_not_found_install, Toast.LENGTH_SHORT).show();
           
        	// missing data, install it
            Intent installIntent = new Intent();
            installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
            startActivity(installIntent);
        }else{
            // Check the documentation for other possible result codes.
            // For example, the language may be available for the locale,
            // but not for the specified country and variant.

            // The TTS engine has been successfully initialized.
            // Allow the user to press the button for the app to speak again.
            buttonRepeat.setEnabled(true);
            
            if(countryDisplayName != null && countryDisplayName.equalsIgnoreCase("") == false){
                Button button = (Button) findViewById(R.id.countries_list);
                button.setText(countryDisplayName);	
            }
            
            mTts.setLanguage(new Locale(language, country));
        }
    }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
	    if (requestCode == MY_DATA_CHECK_CODE) {
	        if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
				mTts = new TextToSpeech(context, onInitListener);
	        }else{
	            // missing data, install it
	            Intent installIntent = new Intent();
	            installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
	            startActivity(installIntent);
	        }
	    }
	}
	
	public void about(View view){
        tracker.trackEvent(
                Constants.ANALYTICS_CLICK_CATEGORY,  // Category
                Constants.ANALYTICS_CLICK_ACTION,  // Action
                Constants.ANALYTICS_ABOUT, // Label
                Constants.ANALYTICS_CLICK_VALUE); // Value
        
        tracker.trackPageView(Constants.ANALYTICS_ABOUT);
	}
	
	public void share(View view){
		String body = context.getString(R.string.share_text) + context.getString(R.string.share_link);
		final Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.app_name));
		intent.putExtra(Intent.EXTRA_TEXT, body);

		startActivity(Intent.createChooser(intent, getString(R.string.share_title)));
	
	/*
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("text/html");
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(body));
startActivity(Intent.createChooser(emailIntent, "Email:"));

	 */
		
        tracker.trackEvent(
                Constants.ANALYTICS_CLICK_CATEGORY,  // Category
                Constants.ANALYTICS_CLICK_ACTION,  // Action
                Constants.ANALYTICS_SHARE, // Label
                Constants.ANALYTICS_CLICK_VALUE); // Value
        
        tracker.trackPageView(Constants.ANALYTICS_SHARE);
	}
	
	public void chooseLanguage(View view){
		if(dialogLanguage == null){		
			String title = context.getString(R.string.button_choose_language);
			String[] items = context.getResources().getStringArray(R.array.countries_name);
		
			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			TextView textView = (TextView) inflater.inflate(R.layout.layout_dialog_title, null);
			textView.setText(title);
			
			ListAdapter adapter = new ArrayAdapter<String>(this, R.layout.layout_list_language_item, items);
			//dialogLanguage = Dialogs.getDialogSingleChoice(context, title, items, 0, "", "", languageClick, null, null);
			
			dialogLanguage = Dialogs.getDialogSingleChoiceCustom(context, textView, adapter, languageConfirmed, context.getString(R.string.dialog_accept), context.getString(R.string.dialog_cancel), languageClick, acceptLanguageClick, cancelLanguageClick);	
		}

		dialogLanguage.show();
		
        tracker.trackEvent(
                Constants.ANALYTICS_CLICK_CATEGORY,  // Category
                Constants.ANALYTICS_CLICK_ACTION,  // Action
                Constants.ANALYTICS_CHOOSE_LANGUAGE, // Label
                Constants.ANALYTICS_CLICK_VALUE); // Value
        
        tracker.trackPageView(Constants.ANALYTICS_CHOOSE_LANGUAGE);
	}
	
	private DialogInterface.OnClickListener languageClick = new DialogInterface.OnClickListener() {
		
		public void onClick(DialogInterface dialog, int which) {
			languageSelected = which;
		}
	};
	
	private DialogInterface.OnClickListener acceptLanguageClick = new DialogInterface.OnClickListener() {
		
		public void onClick(DialogInterface dialog, int which) {
			languageConfirmed = languageSelected;
			
			Resources res = context.getResources();
			
			TypedArray array = res.obtainTypedArray(R.array.languages_code);
			language = array.getString(languageConfirmed);
			
			array = res.obtainTypedArray(R.array.countries_code);
			country = array.getString(languageConfirmed);
			
			
			String[] countriesDisplayName = context.getResources().getStringArray(R.array.countries_name);
			countryDisplayName = countriesDisplayName[languageConfirmed];
			
			if(textToSpeechInit == true){
				int result = mTts.isLanguageAvailable(new Locale(language, country));
				setLanguage(result);
			}
		}
	};
	
	private DialogInterface.OnClickListener cancelLanguageClick = new DialogInterface.OnClickListener() {
		
		public void onClick(DialogInterface dialog, int which) {
			languageSelected = languageConfirmed;
		}
	};
}